/**
 * zmn文章模块-文章编辑
 * 文件命名格式：zmn.模块.表/功能.jas
 * @author heguanghua
 * @since 2018/10/18
 */
layui.define(['index', 'form', 'table', 'laypage', 'layedit', 'zmnSelect'], function (exports) {
    var $ = layui.$;
    var form = layui.form;
    var layer = layui.layer;
    var table = layui.table;
    var laypage = layui.laypage;
    var layedit = layui.layedit;
    let zmnSelect = layui.zmnSelect;

    let partCategoryIds = new Array();
    let partSubCategoryIds = new Array();

    if (json.itemParts!=null){
        for (let i = 0; i < json.itemParts.length; i++) {
            if(partCategoryIds.indexOf(json.itemParts[i].partCategoryId) == -1){
                partCategoryIds.push(json.itemParts[i].partCategoryId);
            }
            partSubCategoryIds.push(json.itemParts[i].partSubCategoryId);
        }
    }

    if (json.wmsGoodsCategories != null) {
        for (let i = 0; i < json.wmsGoodsCategories.length; i++) {
            json.wmsGoodsCategories[i].name = json.wmsGoodsCategories[i].text;
            if (partCategoryIds.indexOf(json.wmsGoodsCategories[i].value) > -1){
                json.wmsGoodsCategories[i].selected = true;
                loadSubCategory({name:json.wmsGoodsCategories[i].name,value:json.wmsGoodsCategories[i].value});
            }
        }
        partSubCategoryIds = new Array();
    }

    xmSelect.render({
            el: ('#partCategoryIds'),
            name: "partCategoryIds",
            autoRow: true,
            radio: false,
            toolbar: {
                show: true,
                list: ['ALL', 'CLEAR', 'REVERSE']
            },
            model: {
                label: {
                    type: 'block',
                    block: {
                        //最大显示数量, 0:不限制
                        showCount: 1,
                        //是否显示删除图标
                        showIcon: true,
                    }
                }
            },
            filterable: true,
            tips: "-选择-",
            size: 'mini',
            data: json.wmsGoodsCategories,
            on: function (data) {
                //arr:  当前多选已选中的数据
                var arr = data.arr;
                //change, 此次选择变化的数据,数组
                var change = data.change;
                //isAdd, 此次操作是新增还是删除
                var isAdd = data.isAdd;
                //可以return一个数组, 代表想选中的数据
                //return []
                console.log(change);
                console.log(isAdd);
                console.log(arr);
                if (arr == null || arr.length == 0) {
                    $("#categoryList").empty();
                }
                else {
                    let ids = new Array();
                    for (var i = 0; i < arr.length; i++) {
                        ids.push(arr[i].value.toString());
                    }
                    console.log(ids)
                    $("#categoryList").children().each(function () {
                        let id = $(this).attr("id").split('_')[1];
                        if (ids.indexOf(id) == -1) {
                            $("#category_" + id).remove();
                        }
                    })
                    for (var i = 0; i < arr.length; i++) {
                        if ($("#category_" + arr[i].value).length == 0) {
                            loadSubCategory(arr[i]);
                        }
                    }
                }
            }
        }
    );

    /**
     * 获取二级分类
     */
    function loadSubCategory(obj) {
        $.ajax({
            async: false,
            type: "POST",
            url: "/service/item/listCategory.action?parentId="+obj.value+"&level=2",
            dataType: "json",
            contentType: "application/json",
            success: function (rs) {
                console.log(rs)
                if (rs.status === 200) {
                    let categoryName = obj.name;
                    let selectAll = true;
                    let selectHtml = "";
                    for (var i=0;i<rs.data.length;i++) {
                        selectHtml += '<div class="layui-input-inline" style="width: 120px">';
                        if (partSubCategoryIds.length > 0 && partSubCategoryIds.indexOf(rs.data[i].categId) > -1){
                            selectHtml += '<input type="checkbox" name="subCategoryId" lay-filter="subCategoryId" checked="checked" value="'+obj.value+'_' + rs.data[i].categId + '" title="'+rs.data[i].categName+'" />';
                        }else{
                            selectHtml += '<input type="checkbox" name="subCategoryId" lay-filter="subCategoryId" value="'+obj.value+'_' + rs.data[i].categId + '" title="'+rs.data[i].categName+'" />';
                            selectAll = false;
                        }
                        selectHtml += '</div>';
                    }
                    console.log(selectAll)
                    let  html = '<div id="category_'+obj.value+'" class="layui-form-item">';
                    html += '<label class="layui-form-label">'+categoryName+'：</label>';
                    html += '<div class="layui-input-inline" style="width: 80px">';
                    if (selectAll){
                        html += '<input type="checkbox" name="selectAll" checked="checked" lay-filter="selectAll" value="'+obj.value+'" title="全选" />';
                    }else {
                        html += '<input type="checkbox" name="selectAll" lay-filter="selectAll" value="'+obj.value+'" title="全选" />';
                    }
                    html += '</div>';
                    html += '<div class="layui-input-block" id="sub_category_'+obj.value+'">';
                    html += selectHtml;
                    html+='</div>';

                    $("#categoryList").append(html);

                    form.render('checkbox');


                    // form.on('checkbox(subCategoryId)', function (data) {
                    //     alert(1);
                    // });

                } else {
                    parent.layui.layer.msg(rs.message, {"icon": 2, area: '750px'});
                    return false;
                }
            }
        });
    }
    form.on('checkbox(selectAll)', function (data) {
        $("#sub_category_"+data.value+" :checkbox").prop("checked", data.elem.checked);
        form.render('checkbox');
    });
    form.on('checkbox(subCategoryId)', function (data) {
        let subCategoryDiv = $(data.elem).parent().parent();
        if (subCategoryDiv.find('input[type=checkbox]').length == subCategoryDiv.find('input[type=checkbox]:checked').length){
            if (!subCategoryDiv.parent().find("input[name=selectAll]").is(":checked")) {
                subCategoryDiv.parent().find("input[name=selectAll]").prop("checked", true);
                form.render('checkbox');
            }
        }else{
            if (subCategoryDiv.parent().find("input[name=selectAll]").is(":checked")) {
                subCategoryDiv.parent().find("input[name=selectAll]").prop("checked", false);
                form.render('checkbox');
            }
        }
    });

    // 提交
    form.on('submit(zmn-form-submit)', function(obj){
        let data = obj.field;
        let partSubCategoryIds = new Array();
        $("input[name=subCategoryId]:checked").each(function(){
            partSubCategoryIds.push($(this).val());
        })
        console.log(partSubCategoryIds);
        data.partSubCategoryIds = partSubCategoryIds;
        // console.log(data)
        submitData(data);
        return false;
    });
    function submitData(data){
        $.ajax({
            async: false,
            type: "POST",
            url: "/service/item/addEditPart.action",
            dataType: "json",
            contentType: "application/json",
            data: JSON.stringify(data),
            success: function (rs) {
                if (rs.status === 200) {
                    parent.layui.layer.msg(rs.message);
                    return false;

                }else {
                    parent.layui.layer.msg(rs.message,{"icon":2,area:'750px'});
                    return false;
                }
            }
        });
    }


    //对外暴露的接口
    exports('serv_service_item_partList', {});
});